from rest_framework import status


def info_of_user(sf, gen_obj=None, request=None):
    try:
        gen_info_objects_list = gen_obj.objects.filter(
            owner=request.user).order_by('-pk')
    except gen_obj.DoesNotExist:
        data = {
            'msg': '您没有创建相对应的患者',
            'status': status.HTTP_400_BAD_REQUEST
        }
        return data
    gen_list = sf.filter_queryset(gen_info_objects_list)
    page = sf.paginate_queryset(gen_list)

    # #######
    # set_session_list(request=request, gen_objects=gen_list)

    data = {
        'data': None,
        'type': None,
    }

    if page:
        serializer = sf.get_serializer(page, many=True)
        data['type'] = 'page_serializer'
        data['data'] = serializer.data
        return data
    serializer = sf.get_serializer(instance=gen_list, many=True)
    data['type'] = 'one_serializer'
    data['data'] = serializer.data
    return data


def info_of_pk(pk, obj, serializer, o_serializer, request):
    try:
        instance = obj.objects.get(id=pk)
    except obj.DoesNotExist:
        data = {
            'msg': '该对应患者信息不存在',
            'status': status.HTTP_400_BAD_REQUEST,
        }
        return data
    s = serializer(instance=instance, context={'request': request})
    data = {
        'info': s.data,
    }
    other_s = o_serializer(
        instance=instance, context={'request': request})
    data.update(other_s.data)
    return data


def retrieve_info_view(pk, sf, obj, request, serializer, o_serializer):
    if pk == 'user':
        data = info_of_user(sf, gen_obj=obj, request=request)
    else:
        data = info_of_pk(pk, obj, serializer, o_serializer, request)
    return data


def reload_list_in_view(sf, req, objs=None, serializer_own=None, types=None):
    data = dict()
    if not types:
        queryset = sf.filter_queryset(sf.get_queryset())
    else:
        queryset = objs

    page = sf.paginate_queryset(queryset)

    try:
        search_id_list = [obj.id for obj in queryset]
    except Exception:
        search_id_list = []

    # if not serializer_own:
    #     if page:
    #         serializer = sf.get_serializer(page, many=True)
    #     else:
    #         serializer = sf.get_serializer(queryset, many=True)

    if page:
        serializer = serializer_own(page,
                                    context={'request': req},
                                    many=True)
        data['type'] = 'page_serializer'
    else:
        serializer = serializer_own(queryset, many=True)
        data['type'] = 'one_serializer'

    data['data'] = serializer.data

    return (data, page, search_id_list)
